
package com.hlkj.pay.app.merchant.ext.impl.icbcpay.ext;
/*
 * Hlpay-Plus aggregate payment system.
 * Copyright (c) 2024-2025 Hlpay Team Copyright has the right of final interpretation.
 */

import com.hlkj.framework.common.util.json.JsonUtils;
import com.hlkj.pay.app.merchant.ext.dto.order.ChannelPayOrderQueryContext;
import com.hlkj.pay.app.merchant.ext.dto.order.ChannelRefundPayOrderContext;
import com.hlkj.pay.app.merchant.ext.impl.icbcpay.constant.IcbcPayConstant;
import com.hlkj.pay.app.merchant.ext.impl.icbcpay.dto.IcbcPayConfig;
import com.hlkj.pay.app.merchant.ext.impl.icbcpay.dto.IcbcpayAppChannelParams;
import com.hlkj.pay.app.merchant.ext.impl.icbcpay.dto.req.OrderQueryReq;
import com.hlkj.pay.app.merchant.ext.impl.icbcpay.dto.req.OrderRefundQueryReq;
import com.hlkj.pay.app.merchant.ext.impl.icbcpay.dto.req.OrderRefundReq;
import com.hlkj.pay.app.merchant.ext.impl.icbcpay.dto.rsp.OrderQueryRsp;
import com.hlkj.pay.app.merchant.ext.impl.icbcpay.dto.rsp.OrderRefundRsp;
import com.hlkj.pay.app.merchant.ext.impl.icbcpay.utils.HttpUtils;
import com.hlkj.pay.app.merchant.ext.impl.icbcpay.utils.IcbcPaySignUtil;
import com.hlkj.pay.enums.PayOrderEnums;
import com.hlkj.pay.infrastructure.model.merchant.MerchantAppChannelDO;
import com.hlkj.pay.infrastructure.model.order.PayOrderDO;
import com.hlkj.pay.infrastructure.model.order.RefundOrderDO;
import com.hlkj.pay.infrastructure.model.pay.ProviderChannelConfigDO;
import com.hlkj.pay.util.DateUtils;
import com.hlkj.pay.util.MerchantUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

/**
 * 工行支付 正扫 反扫 通用处理
 * 
 * @author HlpayTeam
 * @date 2024/10/11 16:22
 */
@Slf4j
@Repository
@RequiredArgsConstructor
public class IcbcPaySceneCommonPayOrder {

    /**
     * 工行支付查询支付订单
     *
     * @param channelPayOrderQueryContext
     */
    public void commonQueryChannelPayOrder(ChannelPayOrderQueryContext channelPayOrderQueryContext) {
        ProviderChannelConfigDO providerChannelConfigDO = channelPayOrderQueryContext.getProviderChannelConfigDO();
        String channelConfig = providerChannelConfigDO.getParamsConfig();
        // 配置转换
        IcbcPayConfig payConfig = getPayConfig(channelConfig, channelPayOrderQueryContext.getMerchantAppChannelDO());
        PayOrderDO payOrderDO = channelPayOrderQueryContext.getPayOrderDO();
        try {
            OrderQueryReq orderQueryReq = new OrderQueryReq();
            orderQueryReq.setPartnerNo(payConfig.getPartnerNo());
            orderQueryReq.setTransDate(DateUtils.getCurrentTime().toString());
            orderQueryReq.setTransNonce(DateUtils.getCurrentTime().toString());
            orderQueryReq.setOutTradeNo(payOrderDO.getPayOrderNo());
            orderQueryReq.setSignature(IcbcPaySignUtil.sign(orderQueryReq, payConfig.getMchPrivateKey()));

            log.info("工行支付订单查询req参数:{}", JsonUtils.toJsonString(orderQueryReq));
            String url = domain(channelPayOrderQueryContext.isTest()) + IcbcPayConstant.TRADE_QUERY;
            String response = HttpUtils.post(url, orderQueryReq);
            log.info("工行支付订单查询返回参数:{}", response);

            // 响应报文验签
            OrderQueryRsp rspBody = JsonUtils.parseObject(response, OrderQueryRsp.class);
            if ("00000000".equals(rspBody.getCode())) {
                PayOrderDO updartePayOrderDO = new PayOrderDO();
                switch (rspBody.getTradeStatus()) {
                    case "SUCCESS":
                        updartePayOrderDO.setState(PayOrderEnums.PAY_ORDER_STATUS.SUCCESS.getCode());
                        updartePayOrderDO.setChannelFeeAmount(MerchantUtils.fenToYuan(rspBody.getTradeFee()));
                        updartePayOrderDO.setSuccessTime(DateUtils.shanghaiDate(rspBody.getPayFinishTime()));
                        break;
                    case "CLOSE":
                        updartePayOrderDO.setState(PayOrderEnums.PAY_ORDER_STATUS.CLOSE.getCode());
                        break;
                    case "PAYING":
                    case "INIT":
                        updartePayOrderDO.setState(PayOrderEnums.PAY_ORDER_STATUS.PAYING.getCode());
                        break;
                    default:
                        updartePayOrderDO.setState(PayOrderEnums.PAY_ORDER_STATUS.FAIL.getCode());
                }

                updartePayOrderDO.setInsOrderNo(rspBody.getTradeNo());
                channelPayOrderQueryContext.setUpdartePayOrderDO(updartePayOrderDO);
            }
            else {
                String respDesc = rspBody.getMessage();
                channelPayOrderQueryContext.setProcessStatus(Boolean.FALSE);
                if (StringUtils.hasText(respDesc)) {
                    channelPayOrderQueryContext.setRemark(respDesc);
                }
                else {
                    channelPayOrderQueryContext.setRemark("工行支付提交支付订单查询返回错误信息为空,错误码为:" + rspBody.getCode());
                }
            }
        }
        catch (Exception e) {
            e.printStackTrace();
            log.error("工行支付查询支付订单请求失败 message:{}", e.getMessage(), e);
            channelPayOrderQueryContext.setRemark("工行支付查询支付订单请求失败,失败信息" + e.getMessage());
            channelPayOrderQueryContext.setProcessStatus(Boolean.FALSE);
        }
    }

    /**
     * 工行支付关闭订单
     *
     * @param channelPayOrderQueryContext
     */
    public void commonCloseChannelPayOrder(ChannelPayOrderQueryContext channelPayOrderQueryContext) {
        ProviderChannelConfigDO providerChannelConfigDO = channelPayOrderQueryContext.getProviderChannelConfigDO();
        String channelConfig = providerChannelConfigDO.getParamsConfig();
        // 配置转换
        IcbcPayConfig payConfig = getPayConfig(channelConfig, channelPayOrderQueryContext.getMerchantAppChannelDO());
        PayOrderDO payOrderDO = channelPayOrderQueryContext.getPayOrderDO();
        try {
            OrderQueryReq orderQueryReq = new OrderQueryReq();
            orderQueryReq.setPartnerNo(payConfig.getPartnerNo());
            orderQueryReq.setTransDate(DateUtils.getCurrentTime().toString());
            orderQueryReq.setTransNonce(DateUtils.getCurrentTime().toString());
            orderQueryReq.setOutTradeNo(payOrderDO.getPayOrderNo());
            orderQueryReq.setSignature(IcbcPaySignUtil.sign(orderQueryReq, payConfig.getMchPrivateKey()));

            log.info("工行支付订单关闭req参数:{}", JsonUtils.toJsonString(orderQueryReq));
            String url = domain(channelPayOrderQueryContext.isTest()) + IcbcPayConstant.TRADE_QUERY;
            String response = HttpUtils.post(url, orderQueryReq);
            log.info("工行支付订单关闭返回参数:{}", response);

            // 响应报文验签
            OrderQueryRsp rspBody = JsonUtils.parseObject(response, OrderQueryRsp.class);
            if ("00000000".equals(rspBody.getCode())) {
                PayOrderDO updartePayOrderDO = new PayOrderDO();
                updartePayOrderDO.setState(PayOrderEnums.PAY_ORDER_STATUS.CLOSE.getCode());
                channelPayOrderQueryContext.setUpdartePayOrderDO(updartePayOrderDO);
            }
            else {
                String respDesc = rspBody.getMessage();
                channelPayOrderQueryContext.setProcessStatus(Boolean.FALSE);
                if (StringUtils.hasText(respDesc)) {
                    channelPayOrderQueryContext.setRemark(respDesc);
                }
                else {
                    channelPayOrderQueryContext.setRemark("工行支付订单关闭返回错误信息为空,错误码为:" + rspBody.getCode());
                }
            }
        }
        catch (Exception e) {
            e.printStackTrace();
            log.error("工行支付关闭支付订单请求失败 message:{}", e.getMessage(), e);
            channelPayOrderQueryContext.setRemark("工行支付关闭支付订单请求失败,失败信息" + e.getMessage());
            channelPayOrderQueryContext.setProcessStatus(Boolean.FALSE);
        }
    }

    /**
     * 工行支付查询关闭订单状态
     *
     * @param channelPayOrderQueryContext
     */
    public void commonQueryChannelClosePayOrder(ChannelPayOrderQueryContext channelPayOrderQueryContext) {
        // 工行支付无此接口
        PayOrderDO updartePayOrderDO = new PayOrderDO();
        updartePayOrderDO.setState(PayOrderEnums.PAY_ORDER_STATUS.CLOSE.getCode());
        channelPayOrderQueryContext.setUpdartePayOrderDO(updartePayOrderDO);
    }

    /**
     * 工行支付订单退款
     *
     * @param channelRefundPayOrderContext
     */
    public void commonRefundChannelPayOrder(ChannelRefundPayOrderContext channelRefundPayOrderContext) {
        ProviderChannelConfigDO providerChannelConfigDO = channelRefundPayOrderContext.getProviderChannelConfigDO();
        String channelConfig = providerChannelConfigDO.getParamsConfig();
        // 配置转换
        IcbcPayConfig payConfig = getPayConfig(channelConfig, channelRefundPayOrderContext.getMerchantAppChannelDO());

        PayOrderDO payOrderDO = channelRefundPayOrderContext.getPayOrderDO();
        RefundOrderDO refundOrderDO = channelRefundPayOrderContext.getRefundOrderDO();
        try {

            OrderRefundReq orderQueryReq = new OrderRefundReq();
            orderQueryReq.setPartnerNo(payConfig.getPartnerNo());
            orderQueryReq.setTransDate(DateUtils.getCurrentTime().toString());
            orderQueryReq.setOriginalTradeNo(payOrderDO.getInsOrderNo());
            orderQueryReq.setOutRefundNo(refundOrderDO.getRefundOrderNo());
            orderQueryReq.setRemark(refundOrderDO.getRefundReason());
            orderQueryReq.setNotifyUrl(channelRefundPayOrderContext.getNotifyUrl());
            orderQueryReq.setRefundAmount(MerchantUtils.YuanToFen(refundOrderDO.getRefundAmount()));
            orderQueryReq.setTransNonce(refundOrderDO.getRefundOrderNo());
            orderQueryReq.setSignature(IcbcPaySignUtil.sign(orderQueryReq, payConfig.getMchPrivateKey()));

            log.info("工行支付订单退款req参数:{}", JsonUtils.toJsonString(orderQueryReq));
            String url = domain(channelRefundPayOrderContext.isTest()) + IcbcPayConstant.REFUND_ORDER;
            String response = HttpUtils.post(url, orderQueryReq);
            log.info("工行支付订单退款返回参数:{}", response);

            // 响应报文验签
            OrderRefundRsp ordeRsp = JsonUtils.parseObject(response, OrderRefundRsp.class);
            if ("00000000".equals(ordeRsp.getCode())) {
                RefundOrderDO updateRefundOrderDO = new RefundOrderDO();
                if ("SUCCESS".equals(ordeRsp.getRefundStatus())) {
                    updateRefundOrderDO.setRefundStatus(PayOrderEnums.REFUND_STATUS.REFUND.getCode());
                    updateRefundOrderDO.setSuccessTime(System.currentTimeMillis());
                } else if ("FAIL".equals(ordeRsp.getRefundStatus())) {
                    updateRefundOrderDO.setRefundStatus(PayOrderEnums.REFUND_STATUS.FAIL.getCode());
                } else
                    updateRefundOrderDO.setRefundStatus(PayOrderEnums.REFUND_STATUS.REFUNDING.getCode());

                channelRefundPayOrderContext.setUpdateRefundOrderDO(updateRefundOrderDO);
            }
            else {
                String respDesc = ordeRsp.getMessage();
                channelRefundPayOrderContext.setProcessStatus(Boolean.FALSE);
                if (StringUtils.hasText(respDesc)) {
                    channelRefundPayOrderContext.setRemark(respDesc);
                }
                else {
                    channelRefundPayOrderContext.setRemark("工行支付提交退款订单返回错误信息为空,错误码为:" + ordeRsp.getCode());
                }
            }
        }
        catch (Exception e) {
            e.printStackTrace();
            log.error("工行支付提交退款订单请求失败 message:{}", e.getMessage(), e);
            channelRefundPayOrderContext.setRemark("工行支付提交退款订单请求失败,失败信息" + e.getMessage());
            channelRefundPayOrderContext.setProcessStatus(Boolean.FALSE);
        }
    }

    /**
     * 工行支付订单退款状态查询
     *
     * @param channelRefundPayOrderContext
     */
    public void commonQueryRefundChannelPayOrder(ChannelRefundPayOrderContext channelRefundPayOrderContext) {
        ProviderChannelConfigDO providerChannelConfigDO = channelRefundPayOrderContext.getProviderChannelConfigDO();
        String channelConfig = providerChannelConfigDO.getParamsConfig();
        // 配置转换
        IcbcPayConfig payConfig = getPayConfig(channelConfig, channelRefundPayOrderContext.getMerchantAppChannelDO());

        RefundOrderDO refundOrderDO = channelRefundPayOrderContext.getRefundOrderDO();
        try {

            OrderRefundQueryReq request = new OrderRefundQueryReq();
            request.setPartnerNo(payConfig.getPartnerNo());
            request.setTransDate(DateUtils.getCurrentTime().toString());
            request.setTransNonce(DateUtils.getCurrentTime().toString());
            request.setOutRefundNo(refundOrderDO.getRefundOrderNo());
            request.setSignature(IcbcPaySignUtil.sign(request, payConfig.getMchPrivateKey()));

            log.info("工行支付订单退款查询req参数:{}", JsonUtils.toJsonString(request));
            String url = domain(channelRefundPayOrderContext.isTest()) + IcbcPayConstant.REFUND_QUERY;
            String response = HttpUtils.post(url, request);
            log.info("工行支付订单退款查询返回参数:{}", response);

            OrderRefundRsp rspBody = JsonUtils.parseObject(response, OrderRefundRsp.class);
            if ("00000000".equals(rspBody.getCode())) {
                RefundOrderDO updateRefundOrderDO = new RefundOrderDO();
                switch (rspBody.getRefundStatus()) {
                    case "SUCCESS":
                        updateRefundOrderDO.setRefundStatus(PayOrderEnums.REFUND_STATUS.REFUND.getCode());
                        updateRefundOrderDO.setSuccessTime(System.currentTimeMillis());
                        break;
                    case "FAIL":
                    case "CLOSE":
                        updateRefundOrderDO.setRefundStatus(PayOrderEnums.REFUND_STATUS.FAIL.getCode());
                        break;
                    default:
                        updateRefundOrderDO.setRefundStatus(PayOrderEnums.REFUND_STATUS.REFUNDING.getCode());
                        break;
                }
                channelRefundPayOrderContext.setUpdateRefundOrderDO(updateRefundOrderDO);
            }
            else {
                String respDesc = rspBody.getMessage();
                channelRefundPayOrderContext.setProcessStatus(Boolean.FALSE);
                if (StringUtils.hasText(respDesc)) {
                    channelRefundPayOrderContext.setRemark(respDesc);
                }
                else {
                    channelRefundPayOrderContext.setRemark("工行支付提交退款订单返回错误信息为空,错误码为:" + rspBody.getCode());
                }
            }
        }
        catch (Exception e) {
            e.printStackTrace();
            log.error("工行支付退款订单查询请求失败 message:{}", e.getMessage(), e);
            channelRefundPayOrderContext.setRemark("工行支付退款订单查询请求失败,失败信息" + e.getMessage());
            channelRefundPayOrderContext.setProcessStatus(Boolean.FALSE);
        }
    }

    public IcbcpayAppChannelParams appChannelParams(MerchantAppChannelDO merchantAppChannelDO) {
        return JsonUtils.parseObject(merchantAppChannelDO.getAppConfigJson(), IcbcpayAppChannelParams.class);
    }

    public String domain(boolean test) {
        return IcbcPayConstant.PAY_ORDER_DOMAIN_PROD;
    }

    public Integer expireMinute(Long time) {
        if (time == null) {
            return 30;
        }
        return (int) (time - System.currentTimeMillis()) / 1000 / 60;
    }

    //转换是如果商户有单独配置 取商户配置
    public IcbcPayConfig getPayConfig(String channelConfig, MerchantAppChannelDO merchantAppChannelDO) {
        // 配置转换
        IcbcPayConfig payConfig = JsonUtils.parseObject(channelConfig, IcbcPayConfig.class);

        IcbcpayAppChannelParams dffpayAppChannelParams = appChannelParams(merchantAppChannelDO);

        if (StringUtils.hasText(dffpayAppChannelParams.getMchPrivateKey()))
            payConfig.setMchPrivateKey(dffpayAppChannelParams.getMchPrivateKey());

        if (StringUtils.hasText(dffpayAppChannelParams.getPublicKey()))
            payConfig.setPublicKey(dffpayAppChannelParams.getPublicKey());

        if (StringUtils.hasText(dffpayAppChannelParams.getMerchantNo()))
            payConfig.setMerchantNo(dffpayAppChannelParams.getMerchantNo());

        if (StringUtils.hasText(dffpayAppChannelParams.getPartnerNo()))
            payConfig.setPartnerNo(dffpayAppChannelParams.getPartnerNo());
        return payConfig;
    }
}
